package com.hhf.rpc.easy.handler;

import com.hhf.rpc.easy.model.RpcRequest;
import com.hhf.rpc.easy.model.RpcResponse;
import com.hhf.rpc.easy.registry.LocalRegistry;
import com.hhf.rpc.easy.serializer.Serializer;
import com.hhf.rpc.easy.serializer.impl.JdkSerializer;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;

import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @Author hhf
 * @Date 2024/10/15
 * @Description
 */
public class HttpServerHandler implements Handler<HttpServerRequest> {


    @Override
    public void handle(HttpServerRequest request) {

        //序列化器
        final Serializer serializer = new JdkSerializer();

        //记录日志
        System.out.println("vertx服务器接收到request:\n请求方法:" + request.method() + "\n请求地址:" + request.uri());

        //异步处理http请求
        request.bodyHandler(body -> {

            //获取请求体的数据
            byte[] bytes = body.getBytes();
            RpcRequest rpcRequest = null;
            try {
                rpcRequest = serializer.deSerialize(bytes, RpcRequest.class);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            //构造请求对象
            RpcResponse rpcResponse = new RpcResponse();
            if (rpcResponse == null){
                rpcResponse.setMessage("rpcResponse is null");
                doResponse(request, rpcResponse, serializer);
                return;
            }

            //通过反射调用服务实现类
            try {
                Class<?> implClass = LocalRegistry.get(rpcRequest.getServiceName());
                Method method = implClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
                Object invoke = method.invoke(implClass.getDeclaredConstructor().newInstance(), rpcRequest.getArgs());
                //封装结果
                rpcResponse.setData(invoke);
                rpcResponse.setDataType(method.getReturnType());
                rpcResponse.setMessage("ok");
            } catch (Exception e) {
                e.printStackTrace();
                rpcResponse.setException(e);
                rpcResponse.setMessage(e.getMessage());
            }
            //异步处理Http响应
            doResponse(request, rpcResponse, serializer);
        });



    }


    private void doResponse(HttpServerRequest request, RpcResponse rpcResponse, Serializer serializer) {
        HttpServerResponse httpServerResponse = request.response()
                .putHeader("content-type", "text/plain");

        try {
            //序列化
            byte[] bytes = serializer.serialize(rpcResponse);
            httpServerResponse.end(Buffer.buffer(bytes));
        } catch (IOException e) {
            e.printStackTrace();
            httpServerResponse.end(Buffer.buffer());
        }

    }
}
